package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        //查询
        List<SpecGroup> groupList = query().eq("category_id", categoryId).list();
        //转换
        List<SpecGroupDTO> dtoList = groupList.stream().map(SpecGroupDTO::new).collect(Collectors.toList());
        //健壮性判断及返回
        if(CollectionUtils.isEmpty(dtoList)){
            return dtoList;
        }

        //查询所有的params
        List<SpecParamDTO> list = paramService.querySpecParams(categoryId, null, null);
        //组装到map中
        Map<Long, List<SpecParamDTO>> collect = list.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //组合
        for (SpecGroupDTO specGroupDTO : dtoList) {
            //获得groupId
            Long groupId = specGroupDTO.getId();
            //根据groupId查询params
            List<SpecParamDTO> dtos = collect.get(groupId);
            //添加
            specGroupDTO.setParams(dtos);
        }

        return dtoList;
    }
}